﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using SqliteORM;
using StackExchange.Profiling;

namespace ChgDoc.Entity
{
    [Serializable]
	public abstract class TableBase<T>
	{
		public virtual void Save( )
		{
			using (TableAdapter<T> adapter = TableAdapter<T>.Open())
				adapter.CreateUpdate( this );
		}
		
		protected static void Do( Action<TableAdapter<T>> action ) 
		{
            using (MiniProfiler.Current.Step( "Do " + typeof( T ).Name ))
            {
                using (TableAdapter<T> adapter = TableAdapter<T>.Open())
                    action( adapter );
            }
		}

		protected static TReturn Get<TReturn>( Func<TableAdapter<T>, TReturn> action ) where TReturn : class
		{
            using (MiniProfiler.Current.Step( "Get " + typeof( T ).Name ))
            {
                using (TableAdapter<T> adapter = TableAdapter<T>.Open())
                    return action( adapter );
            }
		}

        private static List<T> _cached;
        protected static List<T> PopulateCache( List<T> list )
        {
            lock (typeof( T ))
                _cached = list;

            return list;
        }

        protected static T FromCache( Func<T, bool> where, Func<T> get )
        {
            lock (typeof( T ))
            {
                if (_cached == null)
                    _cached = new List<T>();
            }

            var item = _cached.FirstOrDefault( where );
            if (item != null)
                return item;

            item = get();
            _cached.Add( item );

            return item;
        }
	}
}
